<script setup>
import { onMounted } from 'vue'
import useDialog from '@/hooks/use-dialog'
import { validate200Words } from '@/utils/form-validate'
import { listRoleMockApi } from '@/api/mock-js/system/role-api'
import { saveUserMockApi } from '@/api/mock-js/system/user-api'

// 分配角色弹窗
defineOptions({
  name: 'DialogUserRole'
})

// 控制弹窗打开关闭属性使用defingModel双向绑定属性
const modelValue = defineModel({ type: Boolean })

const emit = defineEmits(['on-close'])

const formData = reactive({
  userId: undefined,
  roleIds: [],
  roleNames: []
})

// formRef表单通用
// title是弹窗标题
// loadData加载状态
// setInitData是一个方法，用来copy表单数据以来判断是否被修改
// quickSubmit是一个方法，就是使用快捷键进行保存的方法
// save是保存表单数据方法
//close是关闭弹窗方法
const { formRef, title, loadData, save, close, setInitData, quickSubmit } = useDialog(emit, formData, modelValue)


// 表单的规则在表单那里应用
const rules = {
  roleIds: { required: true, message: '请分配用户角色', trigger: 'blur' },
  remarks: { trigger: 'blur', validator: validate200Words }
}

// 获取用户list
const roleList = ref([])
const getRoleList = async () => {
  try {
    const res = await listRoleMockApi({})
    roleList.value = res.data
  } catch (e) {
    throw new Error(e)
  }
}

// 获取分配的角色名
const handleRoleNames = (val) => {
  if (val?.length) {
    formData.roleNames = roleList.value.filter(({ id }) => formData.roleIds.includes(id)).map(({ roleName }) => roleName)
  }
}
onMounted(() => {
  getRoleList()
})
defineExpose({
  title, formData, setInitData
})
</script>

<template>
  <DialogForm :model-value="modelValue" :title="`分配角色${title}`" :id="formData.id" hide-flag align-center width="420px"
    :loading="loadData.loading" @on-save="save(saveUserMockApi, '角色')" @on-close="close" @on-cancel="close">
    <ElForm ref="formRef" :model="formData" v-loading="loadData.loading" :rules="rules" label-width="80px"
      @keyup.enter.prevent="e => quickSubmit(e, () => save(saveUserMockApi, '角色'))">
      <ElFormItem label="角色" prop="roleIds">
        <ElSelect v-model="formData.roleIds" multiple placeholder="请分配角色" @change="handleRoleNames">
          <ElOption v-for="{ id, roleName } in roleList" :key="id" :label="roleName" :value="id" />
        </ElSelect>
      </ElFormItem>
    </ElForm>
  </DialogForm>
</template>
